import { getCity } from "../api";
import { getCityLocal, setCityLocal } from './loaclStorage'

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
    decodeURIComponent(search)
      .replace(/"/g, '\\"')
      .replace(/&/g, '","')
      .replace(/=/g, '":"')
      .replace(/\+/g, ' ') +
    '"}'
  )
}

/**
 * @returns {String}
 */
export function getCurrentCity() {
  const curCity = getCityLocal()
  const BMap = window.BMap
  if(!curCity) {
    return new Promise(resolve => {
      const myCity = new BMap.LocalCity()
      myCity.get(async result => {
        const res = await getCity(result.name)
        const {name, label} = res.city
        resolve({name, label})
        setCityLocal({name, label})
      })
    })
  } else {
    return Promise.resolve(curCity)
  }
}

export { getCityLocal, setCityLocal }
